package com.tn.po.server;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.tn.bo.UserLoginDetails;
import com.tn.dao.UserDAO;

public class PwdResetServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)	throws IOException, ServletException {
		UserDAO uDao = new UserDAO();
		String regHash = request.getQueryString();
		String destination = "";
		if("action=reset".equals(regHash)){
			String username = request.getParameter("username");
			String pwd = request.getParameter("password");
			UserLoginDetails loginDetails = uDao.findUserByUserId(username);
			if(loginDetails != null){
				loginDetails.setPlainTextPassword(pwd);
				String hash = UserLoginDetails.createUserPasswordHash(loginDetails);
				loginDetails.setUserPasswordHash(hash);
				uDao.updateUserLoginDetails(loginDetails);
				destination = "/jsp/index.jsp";
			}
		}else{
			String userId = uDao.findUserRegMapping(regHash);
			HttpSession session = request.getSession(true);
			UserLoginDetails loginDetails = uDao.findUserByUserId(userId);
			
			if(loginDetails != null){
			    //logic to put user verified to true.
				destination = "/jsp/resetPassword.jsp";
			}
		}
		
		if(StringUtils.isEmpty(destination)){
			destination = "/jsp/error.jsp";
		}
		
		RequestDispatcher rd = getServletContext().getRequestDispatcher(
				destination);
		rd.forward(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)

	throws IOException, ServletException {
		
		doGet(request,response);
	}
}
